<template>
  <div class="profile-container">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="8">
        <!-- 个人信息卡片 -->
        <el-card class="profile-card">
          <div class="avatar-wrapper">
            <el-avatar 
              :size="120" 
              :src="avatarUrl" 
              @error="handleAvatarError"
              :fallback="defaultAvatarUrl"
            >
              {{ userInfo?.nickname?.[0]?.toUpperCase() || 'U' }}
            </el-avatar>
            <div class="avatar-actions">
              <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :headers="uploadHeaders"
                :data="uploadData"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :on-error="handleUploadError"
                :before-upload="beforeAvatarUpload"
              >
                <el-button type="primary" size="small">上传头像</el-button>
              </el-upload>
              <el-button type="info" size="small" @click="showPresetDialog = true">
                选择预设头像
              </el-button>
            </div>
          </div>
          <div class="info-display">
            <h2>{{ form.name }}</h2>
            <p>ID: {{ form.userId }}</p>
            <p>性别: {{ genderMap[form.gender] || '未设置' }}</p>
            <p>活动水平: {{ activityLevelMap[form.activityLevel] || '未设置' }}</p>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="24" :md="16">
        <!-- 基本信息表单 -->
        <el-card class="info-form-card">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
              <el-button type="primary" @click="handleSave" :loading="loading">
                保存修改
              </el-button>
            </div>
          </template>
          
          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="100px"
            class="profile-form"
          >
            <el-form-item label="昵称" prop="name">
              <el-input v-model="form.name" placeholder="请输入昵称" />
            </el-form-item>
            
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="form.gender">
                <el-radio value="男">男</el-radio>
                <el-radio value="女">女</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item label="年龄" prop="age">
              <el-input-number 
                v-model.number="form.age" 
                :min="1" 
                :max="120"
                :controls="true"
              />
            </el-form-item>
            
            <el-form-item label="身高(cm)" prop="height">
              <el-input-number 
                v-model.number="form.height" 
                :min="100" 
                :max="250"
                :controls="true"
              />
            </el-form-item>
            
            <el-form-item label="体重(kg)" prop="weight">
              <el-input-number 
                v-model.number="form.weight" 
                :min="30" 
                :max="200"
                :controls="true"
              />
            </el-form-item>
            
            <el-form-item label="活动水平" prop="activityLevel">
              <el-select v-model="form.activityLevel">
                <el-option label="低" value="低" />
                <el-option label="中等" value="中等" />
                <el-option label="高" value="高" />
              </el-select>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 修改密码卡片 -->
        <el-card class="password-card">
          <template #header>
            <div class="card-header">
              <span>修改密码</span>
              <el-button type="primary" @click="handleChangePassword" :loading="passwordLoading">
                确认修改
              </el-button>
            </div>
          </template>
          
          <el-form
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="passwordRules"
            label-width="100px"
          >
            <el-form-item label="当前密码" prop="oldPassword">
              <el-input
                v-model="passwordForm.oldPassword"
                type="password"
                show-password
                placeholder="请输入当前密码"
              />
            </el-form-item>
            
            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="passwordForm.newPassword"
                type="password"
                show-password
                placeholder="请输入新密码"
              />
            </el-form-item>
            
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="passwordForm.confirmPassword"
                type="password"
                show-password
                placeholder="请再次输入新密码"
              />
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加预设头像选择对话框 -->
    <el-dialog
      v-model="showPresetDialog"
      title="选择预设头像"
      width="50%"
    >
      <div class="preset-avatars">
        <div
          v-for="avatar in presetAvatars"
          :key="avatar"
          class="preset-avatar-item"
          @click="handlePresetAvatarSelect(avatar)"
        >
          <el-avatar
            :size="100"
            :src="`http://localhost:8080/static/images/avatar/${avatar}.jpg`"
            @error="(e) => e.target.src = defaultAvatarUrl"
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const store = useStore()
const formRef = ref(null)
const passwordFormRef = ref(null)
const loading = ref(false)
const passwordLoading = ref(false)
const router = useRouter()

const userInfo = computed(() => store.state.user.userInfo)
const avatarUrl = ref('')

// 使用环境变量定义基础URL和默认头像
// const BASE_URL = process.env.VUE_APP_API_URL || 'http://localhost:8080'
const defaultAvatarUrl = ref('https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png')

// 目标类型映射
// 表单数据
const form = reactive({
  profileId: '',
  userId: '',
  name: '',
  gender: '',
  age: 0,
  height: 170,
  weight: 60,
  activityLevel: '低',
  updatedAt: null
})

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', min: 1, max: 120, message: '年龄必须在 1-120 之间', trigger: 'blur' }
  ],
  height: [
    { required: true, message: '请输入身高', trigger: 'blur' },
    { type: 'number', min: 100, max: 250, message: '身高必须在 100-250 之间', trigger: 'blur' }
  ],
  weight: [
    { required: true, message: '请输入体重', trigger: 'blur' },
    { type: 'number', min: 30, max: 200, message: '体重必须在 30-200 之间', trigger: 'blur' }
  ],
  activityLevel: [
    { required: true, message: '请选择活动水平', trigger: 'change' }
  ]
}

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validatePass2, trigger: 'blur' }
  ]
}

// 上传相关配置
const uploadUrl = '/api/user/avatar'
const uploadHeaders = computed(() => ({
  Authorization: `Bearer ${localStorage.getItem('token')}`
}))
const uploadData = computed(() => ({
  userId: store.state.user.userId
}))

// 头像上传成功处理
const handleAvatarSuccess = (response) => {
  if (response?.code === 200 || response?.success) {
    // 强制更新头像（添加时间戳避免缓存）
    updateAvatarUrl()
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error(response?.message || '上传失败')
  }
}

// 头像加载失败处理
const handleAvatarError = () => {
  console.warn('Avatar loading failed, using default avatar')
  avatarUrl.value = defaultAvatarUrl.value
  // 延迟重试一次
  setTimeout(() => {
    updateAvatarUrl()
  }, 1000)
}

// 头像上传失败处理
const handleUploadError = (error) => {
  console.error('头像上传失败:', error)
  ElMessage.error('头像上传失败，请重试')
}

// 上传前的验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }
  return true
}

// 保存基本信息
const handleSave = () => {
  formRef.value.validate(async valid => {
    if (valid) {
      try {
        loading.value = true
        const response = await fetch('/api/user/profile', {
          method: 'PUT',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            profileId: form.profileId,
            userId: form.userId,
            name: form.name,
            gender: form.gender,
            age: form.age,
            height: form.height,
            weight: form.weight,
            activityLevel: form.activityLevel,
            updatedAt: form.updatedAt
          })
        })
        
        const result = await response.json()
        if (result.success && result.code === 200) {
          ElMessage.success('保存成功')
        } else {
          throw new Error(result.message || '保存失败')
        }
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error(error.message || '保存失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 修改密码处理函数
const handleChangePassword = () => {
  passwordFormRef.value.validate(async valid => {
    if (valid) {
      try {
        passwordLoading.value = true
        const userId = localStorage.getItem('userId')
        const response = await fetch(`/api/user/password?userId=${userId}&oldPassword=${passwordForm.oldPassword}&newPassword=${passwordForm.newPassword}`, {
          method: 'PUT',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          }
        })
        
        const result = await response.json()
        if (result.success && result.code === 200) {
          ElMessage.success('密码修改成功')
          // 清空表单
          passwordForm.oldPassword = ''
          passwordForm.newPassword = ''
          passwordForm.confirmPassword = ''
        } else {
          throw new Error(result.message || '密码修改失败')
        }
      } catch (error) {
        console.error('密码修改失败:', error)
        ElMessage.error(error.message || '密码修改失败')
      } finally {
        passwordLoading.value = false
      }
    }
  })
}

// 修改预设头像的显示逻辑
const presetAvatars = ref(['default', 'avatar1', 'avatar2', 'avatar3'])  // 直接定义可用的预设头像列表
const showPresetDialog = ref(false)

// 修改预设头像的选择方法
const handlePresetAvatarSelect = async (avatarName) => {
  try {
    const userId = store.state.user.userId
    const token = localStorage.getItem('token')
    const response = await fetch(`/api/user/avatar/preset?userId=${userId}&avatarName=${avatarName}`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    
    const result = await response.json()
    if (result.success && result.code === 200) {
      // 先更新头像
      await updateAvatarUrl()
      // 更新成功后再关闭对话框
      showPresetDialog.value = false
      ElMessage.success('头像更新成功')
    } else {
      throw new Error(result.message || '更新头像失败')
    }
  } catch (error) {
    console.error('更新头像失败:', error)
    ElMessage.error(error.message || '更新头像失败')
  }
}

// 在 onMounted 中调用
onMounted(async () => {
  try {
    const userId = localStorage.getItem('userId')
    if (!userId) {
      avatarUrl.value = defaultAvatarUrl.value
      ElMessage.error('请先登录')
      router.push('/login')
      return
    }

    // 先设置默认头像
    avatarUrl.value = defaultAvatarUrl.value
    
    // 获取用户信息
    const response = await fetch(`/api/user/profile?userId=${userId}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    const result = await response.json()
    
    if (result.success && result.code === 200) {
      // 更新表单数据
      Object.assign(form, {
        profileId: result.data.profileId,
        userId: result.data.userId,
        name: result.data.name,
        gender: result.data.gender,
        age: Number(result.data.age),
        height: Number(result.data.height),
        weight: Number(result.data.weight),
        activityLevel: result.data.activityLevel || '低',
        updatedAt: result.data.updatedAt
      })
    } else {
      throw new Error(result.message || '获取用户信息失败')
    }
    
    // 更新头像
    updateAvatarUrl()
  } catch (error) {
    console.error('获取用户信息失败:', error)
    avatarUrl.value = defaultAvatarUrl.value
    ElMessage.error('获取用户信息失败，请重新登录')
    router.push('/login')
  }
})

// 修改头像URL更新函数
const updateAvatarUrl = async () => {
  const userId = store.state.user.userId
  if (!userId) {
    avatarUrl.value = defaultAvatarUrl.value
    return
  }

  try {
    const token = localStorage.getItem('token')
    const response = await fetch(`/api/user/avatar?userId=${userId}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    const result = await response.json()
    
    if (result.success && result.code === 200) {
      // 直接使用返回的头像URL，添加时间戳避免缓存
      avatarUrl.value = `${result.data}?t=${Date.now()}`
    } else {
      throw new Error(result.message || '获取头像失败')
    }
  } catch (error) {
    console.error('获取头像失败:', error)
    avatarUrl.value = defaultAvatarUrl.value
  }
}

// 添加日期格式化函数
// eslint-disable-next-line no-unused-vars
const formatDate = (dateArray) => {
  if (!dateArray) return ''
  return `${dateArray[0]}-${String(dateArray[1]).padStart(2, '0')}-${String(dateArray[2]).padStart(2, '0')}`
}

// 日期限制

// 修改性别映射
const genderMap = {
  '男': '男',
  '女': '女',
  '未设置': '未设置'
}

// 修改活动水平映射
const activityLevelMap = {
  '低': '低',
  '中等': '中等',
  '高': '高'
}

// 在 setup 中使用
// 修改信息显示部分的模板
</script>

<style lang="scss" scoped>
.profile-container {
  padding: 20px;
  
  .profile-card {
    margin-bottom: 20px;
    
    .avatar-wrapper {
      text-align: center;
      margin-bottom: 20px;
      
      .el-avatar {
        background-color: var(--el-color-primary);
        color: #fff;
        font-size: 24px;
        font-weight: bold;
      }
      
      .avatar-actions {
        margin-top: 16px;
      }
    }
    
    .info-display {
      text-align: center;
      
      h2 {
        margin: 0 0 8px;
      }
      
      p {
        margin: 0 0 16px;
        color: var(--el-text-color-secondary);
      }
    }
  }
  
  .info-form-card {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .profile-form {
      max-width: 600px;
    }
  }
  
  .password-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .el-form {
      max-width: 600px;
    }
  }
}

.avatar-uploader {
  text-align: center;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

// 添加预设头像样式
.preset-avatars {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 20px;
  padding: 20px;
}

.preset-avatar-item {
  cursor: pointer;
  text-align: center;
  transition: transform 0.2s;

  &:hover {
    transform: scale(1.1);
  }
}

.avatar-actions {
  display: flex;
  gap: 10px;
  justify-content: center;
  margin-top: 16px;
}
</style> 